package com.richfun.boot.common.util;

import com.richfun.boot.common.config.JWT;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class HttpContextUtils {

	private static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static String getDomain(){
		HttpServletRequest request = getHttpServletRequest();
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
	}

	public static String getOrigin(){
		HttpServletRequest request = getHttpServletRequest();
		return request.getHeader("Origin");
	}

	/**
	 * 获取当前用户JWT过滤的userId
	 * */
	public static Long getJwtUserId() {
		String userId = getHttpServletRequest().getAttribute(JWT.USER_KEY).toString();
        if (CommonUtil.isBlank(userId)) {
            return null;
        }
		return Long.parseLong(userId);
	}

}
